#include "inserttabledialog.h"
#include "ui_inserttabledialog.h"
#include "datamanagement/mainwindows/mainwindow.h"

insertTableDialog::insertTableDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::insertTableDialog)
{
    ui->setupUi(this);
    // 去掉问号，设置最小化、最大化、关闭
    setWindowFlags(Qt::Dialog | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint);
    setWindowTitle("新增表数据");

    // 加载默认布局
    userDefinedlayout();
}

insertTableDialog::~insertTableDialog()
{
    delete ui;
    // 循环删除界面输入框/下拉框对象
    QList<QObject*> edits =  inputTextMap.values();
    for(QObject* edit: edits) {
        delete edit;
    }
    // 清理映射集
    inputTextMap.clear();
}

void insertTableDialog::on_submit_pushButton_clicked()
{
    // 开启一个加载提示框
    LoadingDialog* loading = LoadingDialog::createLoading(this);

    qDebug()<<"进入插入"+UserDefineConstant::USERDEFINE_TABLE_TABLE_NAME+"数据操作";
    QList<QPair<QString,QString>> columnNameAndValues;
    QList<QString> tableColumnZnNames = inputTextMap.keys();
    QString addTableName;
    QString addTableZnName;
    for(QString tableColumnZnName: tableColumnZnNames) {
        QString tableColumnName = tableZnNameAndTbaleNames.value(tableColumnZnName);
        QLineEdit* lineEdit = (QLineEdit*) inputTextMap.value(tableColumnZnName);
        QString text = lineEdit->text().trimmed();
        qDebug()<<"填写数据："<<tableColumnZnName<<"="<<text;
        if(ObjectUtil::isEmpty(text)) {
            loading->close(); // 关闭加载提示框
            QMessageBox::information(this,"提示",tableColumnZnName+"请填写完整");
            return;
        }
        if(tableColumnZnName == UserDefineConstant::USERDEFINE_TABLE_COLUMN_TABLE_NAME_ZN_TITLE) {
            QRegExp rx("^[a-zA-Z_]+$");
            if(rx.indexIn(text) == -1) {
                loading->close(); // 关闭加载提示框
                QMessageBox::information(this,"提示",tableColumnZnName+"请填写英文字母和下划线的组合词");
                return;
            }
            addTableName = text;
        }
        if(tableColumnZnName == UserDefineConstant::USERDEFINE_TABLE_COLUMN_TABLE_ZN_NAME_ZN_TITLE) {
            addTableZnName = text;
        }
        QList<QueryConditions> conditions;
        conditions.append(QueryConditions(tableColumnName, text, false, "=", "and"));
        int count = DataBaseOpt::selectAllCount(UserDefineConstant::USERDEFINE_TABLE_TABLE_NAME, conditions);
        if(count > 0) {
            loading->close(); // 关闭加载提示框
            QMessageBox::information(this,"提示",tableColumnZnName+"已存在，请重新输入");
            return;
        }
        columnNameAndValues.append(qMakePair(tableColumnName, text));
    }
    if(DataBaseManage::getDb().driver()->hasFeature(QSqlDriver::Transactions)) { // 判断是否支持事务
        if(DataBaseManage::getDb().transaction()) { // 判断是否开启事务成功
            QList<bool> isSucess;
            isSucess.append(DataBaseOpt::insertTableData(UserDefineConstant::USERDEFINE_TABLE_TABLE_NAME, columnNameAndValues));
            isSucess.append(DataBaseOpt::createTable(addTableName, QList<QString>(), true));
            if(isSucess.contains(false)) {
                if(!DataBaseManage::getDb().rollback()) {  //回滚
                    qDebug()<< DataBaseManage::getDb().lastError();
                }
            } else {
                if(!DataBaseManage::getDb().commit()) {  //提交
                    qDebug()<< DataBaseManage::getDb().lastError();
                    if(!DataBaseManage::getDb().rollback()) {  //回滚
                        qDebug()<< DataBaseManage::getDb().lastError();
                    }
                }
            }
            loading->close(); // 关闭加载提示框
            if(!isSucess.contains(false)) {
                close();
                // 刷新自定义表对应的列表
                columnSettingDialog* columnSetting = (columnSettingDialog*) parentWidget();
                columnSetting->refreshUserDefineTableData();

                // 刷新表中文名下拉框数据
                columnSetting->refreshTableComboBox();

                // 刷新主界面左侧列表信息，和刷新主界面指定右侧tableZnName表格界面所有界面信息
                ((MainWindow* )UserDefineConstant::MAIN_WINDOW)->refreshClassifyListWidgetAndTableWidgetByTableZnName(addTableZnName);
                QMessageBox::information(this,"成功","插入成功");
            } else {
                QMessageBox::information(this,"失败","插入失败");
            }
        } else {
            loading->close(); // 关闭加载提示框
            QMessageBox::information(this, "失败","开启数据库事务失败，操作失败");
        }
    } else {
        loading->close(); // 关闭加载提示框
        QMessageBox::information(this, "失败","不支持数据库事务，操作失败");
    }
}

void insertTableDialog::userDefinedlayout()
{
    // 删除窗口所有布局
    QLayout *dlayout = layout();
    delete dlayout;

    // 添加自定义表的属性字段中文标题和属性字段的映射关系
    tableZnNameAndTbaleNames.insert(UserDefineConstant::USERDEFINE_TABLE_COLUMN_TABLE_NAME_ZN_TITLE,
                                    UserDefineConstant::USERDEFINE_TABLE_COLUMN_TABLE_NAME);
    tableZnNameAndTbaleNames.insert(UserDefineConstant::USERDEFINE_TABLE_COLUMN_TABLE_ZN_NAME_ZN_TITLE,
                                    UserDefineConstant::USERDEFINE_TABLE_COLUMN_TABLE_ZN_NAME);

    // 构造界面展示的属性名中文标题
    QList<QString> columns;
    columns.append(UserDefineConstant::USERDEFINE_TABLE_COLUMN_TABLE_NAME_ZN_TITLE);
    columns.append(UserDefineConstant::USERDEFINE_TABLE_COLUMN_TABLE_ZN_NAME_ZN_TITLE);
    QGridLayout* gridLayout = new QGridLayout();
    int row = 0;
    // 循环展示的属性中文标题，为每个中文标题添加对应的组件映射
    for(QString columnZnName:columns) {
        gridLayout->addWidget(new QLabel(columnZnName),row,0,1,1); // 界面添加属性lable显示
        QLineEdit* lineEdit = new QLineEdit();
        gridLayout->addWidget(lineEdit,row,1,1,1); // 界面添加属性对应的输入框
        inputTextMap.insert(columnZnName, lineEdit); // 记录属性中文名和组件的映射关系
        row++;
    }

    QPushButton* submitBtn = new QPushButton("添加"); // 构造添加提交按钮
    connect(submitBtn,SIGNAL(clicked()),this,SLOT(on_submit_pushButton_clicked())); // 为添加提交按钮绑定点击事件槽函数
    QVBoxLayout* vBoxLayout = new QVBoxLayout();
    vBoxLayout->addLayout(gridLayout);
    vBoxLayout->addWidget(submitBtn);
    // 设置窗口布局
    setLayout(vBoxLayout);
}
